package net.wantongtech.xa.uploadbasicinfo.util;

import cn.com.taiji.sdk.comm.LwClientHelper;
import cn.com.taiji.sdk.model.comm.protocol.sdts.backlist.CardBlackListAllDownloadRequest;
import cn.com.taiji.sdk.model.comm.protocol.sdts.backlist.CardBlackListIncrDownloadRequest;
import com.zgglyun.common.model.comm.protocol.AbstractBinRequest;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author MaShibo
 * 2021/4/2 0002
 */
@Slf4j
public class BlackListFileUtil {


    public static File downloadCardBlackFileByVersion(String version, String targetPath) throws IOException {
        boolean isInc = version.length() == 12;
        File downloadFile;
        int endIndex = targetPath.lastIndexOf(File.separatorChar);
        String fileName = targetPath.substring(endIndex + 1);
        String targetDir = targetPath.substring(0, endIndex);
        if (isInc) {
            CardBlackListIncrDownloadRequest incDownloadReq = new CardBlackListIncrDownloadRequest();
            incDownloadReq.setVersion(version);
            LwClientHelper.prepareFilename(incDownloadReq);
            downloadFile = downloadFileUntilSuccess(incDownloadReq, targetDir);
        } else {
            CardBlackListAllDownloadRequest fullDownloadReq = new CardBlackListAllDownloadRequest();
            fullDownloadReq.setVersion(version);
            LwClientHelper.prepareFilename(fullDownloadReq);
            downloadFile = downloadFileUntilSuccess(fullDownloadReq, targetDir);
        }
        Path path = Paths.get(downloadFile.getParent(), fileName);
        Files.move(downloadFile.toPath(), path);
        return path.toFile();
    }

    private static File downloadFileUntilSuccess(AbstractBinRequest request, String targetDir) {
        try {
            return LwClientHelper.downLoad(request, targetDir);
        } catch (IOException e) {
            log.error("卡片黑名单文件下载网络异常：{}", e.getMessage());
            return downloadFileUntilSuccess(request, targetDir);
        }
    }
}
